import Vue from 'vue'

// 自定义 v-scroll 指令，解决 ios 中拖动问题
Vue.directive('scroll', {
  bind: function (el, binding) {
    let borderTop = !binding.modifiers.top // 默认设置 border-top
    let borderBottom = !binding.modifiers.bottom // 默认设置 border-bottom

    let is_ios = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    // ios 则添加属于ios的样式
    if (is_ios) {
      let main_class = 'main'
      if (borderTop) main_class += ' main-ios-top'
      if (borderBottom) main_class += ' main-ios-bottom'

      el.className = main_class
      setTimeout(() => {
        // van-pull-refresh 组件好像会销毁 v-scroll 绑定，每次下拉加载后和执行这里，因此这里也要做判断
        if (borderTop) el.scrollTop = 1
      })
      el.addEventListener('scroll', function (ev) {
        if (el.scrollTop === 0 && borderTop) {
          el.scrollTop = 1
        } else if (el.scrollHeight === el.scrollTop + el.clientHeight && borderBottom) {
          el.scrollTop -= 1
        }
      })
    }
  }
})
